<?php
namespace app\controllers;

use app\common\corelib\CacheHelper;
use app\common\WxUtil;
use app\logic\CourseLogic;
use app\logic\UserLogic;
use yii;
//前端试题接口
class TestController extends BaseController
{
    //获取下一道试题
	public function actionGetList()
	{
        $open_id = $this->getQueryparams('open_id',0);
        /*$paper_type = $this->getQueryparams('paper_type',0);
        $chapter_id = $this->getQueryparams('chapter_id',0);*/
        $paper_id = $this->getQueryparams('paper_id',0);
        //$test_id = $this->getQueryparams('test_id',0);

        $courseLogic = new CourseLogic();
        $answer = $courseLogic->getAnswerByOpenId($open_id,$paper_id);
        $firstTest = $courseLogic->getTest($paper_id,0,'',$open_id);
        $lastTest = $courseLogic->getLastTest($paper_id,$open_id);

        $in_user = CacheHelper::get($paper_id.'_in_user');
        if(!$answer || ($in_user && (in_array($open_id,$in_user)))){
            $answer_no = self::GetRandStr(16);
            if($in_user){
                $key = array_search($open_id, $in_user);
                if ($key !== false)
                    array_splice($in_user, $key, 1);
                CacheHelper::set($paper_id.'_in_user',$in_user);
            }
            CacheHelper::set($open_id.$paper_id,$answer_no);
            $res = $courseLogic->getTest($paper_id,0,$answer_no,$open_id,true);
        }elseif($firstTest['test_id']==$answer['test_id'] && $answer['is_correct']==0 && $answer['answer_num']==1){
            $answer_no = CacheHelper::get($open_id.$paper_id);
            $res = $courseLogic->getTest($paper_id,0,'',$open_id);
        }elseif($lastTest['test_id']==$answer['test_id'] && $answer['is_correct']==0 && $answer['answer_num']==1){
            $answer_no = CacheHelper::get($open_id.$paper_id);
            $res = $courseLogic->getLastTest($paper_id);
        }elseif($lastTest['test_id']==$answer['test_id'] && ($answer['is_correct']==1 || $answer['answer_num']==2)){
            $answer_no = self::GetRandStr(16);
            CacheHelper::set($open_id.$paper_id,$answer_no);
            $res = $courseLogic->getTest($paper_id,0,'',$open_id,true);
        }else{
            $answer_no = CacheHelper::get($open_id.$paper_id);
            $res = $courseLogic->getTest($paper_id,$answer['test_id'],$answer_no,$open_id);
        }
        $res['test_options'] = json_decode($res['test_options'],true);
        $res['answer_no'] = $answer_no;


        $all_test = $courseLogic->getAllTest($paper_id,$open_id);
        foreach($all_test AS $kk=>$vv){
            if($vv['test_id']==$res['test_id']){
                $res['test_no'] = $kk+1;
                break;
            }

        }

        $this->response($res);
	}

    private static function GetRandStr($length)
    {
        $str = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $len = strlen($str) - 1;
        $randstr = '';
        for ($i = 0; $i < $length; $i++) {
            $num = mt_rand(0, $len);
            $randstr .= $str[$num];
        }
        return $randstr;
    }
    //回答试题
	public function actionAnswer(){
        $open_id = $this->getQueryparams('open_id',0);
        $paper_id = $this->getQueryparams('paper_id',0);
        $test_id = $this->getQueryparams('test_id',0);
        $answer = $this->getQueryparams('answer',"");
        $answer_no = $this->getQueryparams('answer_no',"");
        $courseLogic = new CourseLogic();
        $test = $courseLogic->getTestById($test_id);
        if($test['test_answer'] == $answer || $test['test_type']==10 || $test['test_type']==20 || $test['test_type']==7){
            $is_correct = 1;
        }else{
            $is_correct = 0;
        }
        $userLogic = new UserLogic();
        $user = $userLogic->findByOpenid($open_id);
        $answer_num = $courseLogic->answer($user['user_id'],$test_id,$answer,$paper_id,$is_correct,$answer_no);

        $lastTest = $courseLogic->getLastTest($paper_id,$open_id);
        if($lastTest['test_id']==$test_id && ($answer_num==2 || $is_correct==1)){
            $userLogic->addStudyHistory($open_id,2,$paper_id,1);
            $is_end = 1;
        }else{
            $userLogic->addStudyHistory($open_id,2,$paper_id,0);
            $is_end = 0;
        }
        $this->response(['is_correct'=>$is_correct,'answer_num'=>$answer_num,'is_end'=>$is_end]);
    }

    public function actionGetJssdk(){
        $url = $this->getQueryparams('url','');
        $result['appId'] = \Yii::$app->params['wx']['appid'];
        $result['timestamp'] = time();
        $result['nonceStr'] = self::GetRandStr(16);
        $wxUtil = new WxUtil();
        $jsapiTicket = $wxUtil->getJsSdkTicket();
        $string = "jsapi_ticket=$jsapiTicket&noncestr=".$result['nonceStr']."&timestamp=".$result['timestamp']."&url=$url";
        $signature = sha1($string);
        $result['signature'] = $signature;
        $this->response($result);
    }
    //上传微信文件
    public function actionUpload(){
        $media_id = $this->getQueryparams('media_id','');
        $wxUtil = new WxUtil();
        $access_token = $wxUtil->getAccessToken();

        $path = "./weixinrecord/";   //保存路径，相对当前文件的路径
        $outPath = Yii::$app->params['upload']['audio_domain']."/weixinrecord/";  //输出路径，给show.php 文件用，上一级

        if(!is_dir($path)){
            mkdir($path);
        }

        //微 信上传下载媒体文件
        $url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token={$access_token}&media_id={$media_id}";

        $filename = "wxupload_".time().rand(1111,9999).".amr";
        $this->downAndSaveFile($url,$path."/".$filename);

        $data["path"] = $outPath.$filename;
        $data["msg"] = "download record audio success!";
        // $data["url"] = $url;
        $this->response($data);
    }
    
    private function downAndSaveFile($url,$savePath){
        ob_start();
        readfile($url);
        $img  = ob_get_contents();
        ob_end_clean();
        $size = strlen($img);
        $fp = fopen($savePath, 'a');
        fwrite($fp, $img);
        fclose($fp);
    }



}
